<template lang="pug">
data-page(
  v-bind="pageParams"
  style="padding: 0"
)
  mt-table(
    v-bind="tableProps"
  )
  templatePreview(v-model="templatePreviewShow",:selectRow="hisRegistrationItem ?? {}",@handleQuery="handleQuery")
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type TableProps,
  useNotify,
} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { type QueryPagination, useApi } from "@scmt/core-api";
import {
  type RegistrationEntity,
  type RegistrationQueryParams,
  adviceColumns,
  ERegistrationColumnKey,
  registrationStateColorMap,
  RegistrationStateoptions,
} from "@scmt/api-pacs-registration";
import templatePreview from "./templatePreview.vue";
import { useUser } from "@scmt/common-store";

const user = useUser();
const hisRegistrationItem = defineModel();
const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<RegistrationQueryParams>({
  name: "",
  pageNum: 1,
  pageSize: 20,
  registrationState: 1,
});
const selectRows = ref([]);
const editingObj = ref<null | RegistrationEntity>(null);
const templatePreviewShow = ref(false);
const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const params = Object.assign({ executionOfficeId: user.currentOfficeId ?? "currentOfficeId" }, queryPramas, q);
    return $api.pacs.registration.query(params);
  },
  save: (model: RegistrationEntity) => {
    return $api.pacs.registration.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  batchUpdate: (models: any) => {
    return $api.pacs.registration.batchUpdate(models).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.pacs.registration.destroy(ids).then(() => {
      $notify.success("删除成功");

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  //患者类型字典
  patientType: () => $api.dict.item.listAsOptions("patient-type"),
});

onMounted(() => {
  request("patientType");
  request("tableData");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [

    {
      prop: "outpatientNumber",
      label: "业务编号",
    },
    {
      prop: "inspectionNumber",
      label: "检查编号",
    },
    {
      prop: "name",
      label: "患者姓名",
    },
    {
      prop: "idCard",
      label: "身份证号",
    },

    {
      prop: "patientType",
      label: "患者来源",
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("patient-type"),
      },
    },
    {
      prop: "executionState",
      label: "检查状态",
      as: "select",
      options: {
        multiple: true,
        separator: ",",
        options: RegistrationStateoptions,
      },
    },
  ];

  const headerActions: Action[] = [
    // { label: "进入登记", type: "primary", event: "confirmRegistration" },
    { label: "拒绝执行", type: "danger", event: "refuseExecute" },
    // { label: "批量登记", type: "primary", event: "batchRegistration" },
    { label: "打印申请单", type: "warning", event: "print" },
    //{ label: "打印标签", event: "" },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    columns: 3,
    alignAction: "left",
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    pagerCount: 5,
    columns: [
      {
        label: "序号",
        width: "60px",
        type: "selection",
      },
      adviceColumns[ERegistrationColumnKey.RegistrationStateLable],
      adviceColumns[ERegistrationColumnKey.PatientType],
      adviceColumns[ERegistrationColumnKey.InspectionNumber],
      adviceColumns[ERegistrationColumnKey.AdmissionNumber],
      adviceColumns[ERegistrationColumnKey.Name],
      adviceColumns[ERegistrationColumnKey.Sex],
      adviceColumns[ERegistrationColumnKey.Age],
      adviceColumns[ERegistrationColumnKey.ProjectName],
      adviceColumns[ERegistrationColumnKey.ApplyOfficeName],
      adviceColumns[ERegistrationColumnKey.CreateTime],
    ],
    onAct: onPageActions,
    highlightCurrentRow: true,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    //@ts-ignore
    cellStyle: ({ row, column }) => {
      if (column.property === adviceColumns[ERegistrationColumnKey.RegistrationStateLable].prop) {
        return {
          //@ts-ignore
          backgroundColor: `${registrationStateColorMap[row[column.property]] || ""} !important`,
        }
      }
    },
    onSelectionChange: (row: any) => {
      selectRows.value = row;
    },
    onRowDblclick: (row) => {
      hisRegistrationItem.value = null;
      nextTick(() => {
        hisRegistrationItem.value = row;
      });
    },
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.pacs.registration.$$createEntity(model);
      break;
    case "destroy":
      request("destroy", model ? model.id : "");
      break;
    //确认登记
    case "confirmRegistration":
      hisRegistrationItem.value = null;
      nextTick(() => {
        if (selectRows.value.length == 0) {
          $notify.info("请选择您要登记的数据！！！");
        } else if (selectRows.value.length == 1) {
          hisRegistrationItem.value = selectRows.value[0];
        } else {
          $notify.warning("只允许登记一条数据！！！");
        }
      });
      break;
    //拒绝执行
    case "refuseExecute":
      if (selectRows.value.length == 0) {
        $notify.info("请选择您要拒绝执行的数据！！！");
        break;
      }
      let models = ref<Array<RegistrationEntity>>([]);
      for (const key in selectRows.value) {
        if (Object.prototype.hasOwnProperty.call(selectRows.value, key)) {
          const element = selectRows.value[key];
          let model = $api.pacs.registration.$$createEntity(element);
          if (model) {
            model.executionState = "3";
            models.value.push(model);
          }
        }
      }
      request("batchUpdate", { data: models.value });
      break;
    //批量登记
    case "batchRegistration":
      if (selectRows.value.length == 0) {
        $notify.info("请选择您要登记的数据！！！");
        break;
      }
      let modelArray = ref<Array<RegistrationEntity>>([]);
      for (const key in selectRows.value) {
        if (Object.prototype.hasOwnProperty.call(selectRows.value, key)) {
          const element = selectRows.value[key];
          let model = $api.pacs.registration.$$createEntity(element);
          if (model) {
            model.executionState = "2";
            modelArray.value.push(model);
          }
        }
      }
      request("batchUpdate", { data: modelArray.value });
      break;
    //打印申请单
    case "print":
      hisRegistrationItem.value = null;
      if (selectRows.value.length == 0) {
        $notify.info("请选择您要打印的数据！！！");
      } else if (selectRows.value.length == 1) {
        hisRegistrationItem.value = selectRows.value[0];
        templatePreviewShow.value = true;
      } else {
        $notify.warning("只允许打印一条数据！！！");
      }
      break;
  }
};

//重置查询
const handleQuery = (q: any) => {
  return request("tableData", q);
};

defineExpose({
  handleQuery,
});

//监听科室改变
watch(
  () => user.currentOfficeId,
  (item) => {
    if (item) {
      request("tableData", {});
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped></style>
